<template>
  <div class="home">
    <div class="main">
      <calendar
          :poppable="false"
          :min-date="minDate"
          :max-date="maxDate"
          :title="'天天加班'"
          :row-height="80"
          @select="onSelectDate"
          :formatter="formatter"
          color="#7EAA92"
          @confirm="onConfirm">
        <template #bottom-info="item">
          <div>
            <div class="start">
              {{generateTimeShow(item, 0)}}
            </div>
            <div class="end">
              {{generateTimeShow(item, 1)}}
            </div>
          </div>
        </template>
      </calendar>
    </div>
    <popup v-model="showPicker" round position="bottom">
      <picker
          show-toolbar
          :columns="columns"
          @cancel="onCancel"
          @confirm="onConfirmDate"
      >
        <template #cancel>清空</template>
      </picker>
    </popup>

    <action-sheet v-model="showKeyboard" :closeable="false" :title="keyboardText" @close="$refs.keyboard.reset()">
      <div class="content">
        <time-keyboard ref="keyboard" v-model="keyboardText" @commit="onCommitKeyboardData" @clear="onClear"></time-keyboard>
      </div>
    </action-sheet>

    <router-link to="/ios_shortcuts" class="ios_link">使用iOS快捷指令添加</router-link>
  </div>

</template>

<script>
import {Calendar, Picker, Popup, ActionSheet,   } from 'vant';
import dayjs from 'dayjs'
import TimeKeyboard from '@/components/time_keyboard'

export default {
  name: 'HomeView',
  data(){
    return{
      showPicker: false,
      selectedDate: null,
      columns: null,
      dateList: [],
      showIosButton: false,
      showKeyboard: false,
      keyboardText: '_ _ : _ _ ~ _ _ : _ _'
    }
  },
  components: {
    Calendar, Picker, Popup, ActionSheet, TimeKeyboard
  },
  created() {
    this.initData()
    this.quickAdd()
    this.initIosSettings()
  },
  computed: {
    minDate() {
      let now = new Date()
      let result
      let monthFirstDay = new Date(now.getFullYear(), now.getMonth() , 1)
      const useLastWeekData = localStorage.getItem("useLastWeekData") === '1'
      let weekFirstDay = now
      while (true){
        if(weekFirstDay.getDay() === (useLastWeekData ? 5 : 1)){
          break
        }
        else{
          weekFirstDay = new Date(weekFirstDay.getTime() - 24 * 60 * 60 * 1000)
        }
      }
      if(weekFirstDay.getTime() < monthFirstDay.getTime()){
        let lastMonthFirstDay = new Date(now.getFullYear(), now.getMonth() - 1 , 1)
        result = lastMonthFirstDay
      }
      else{
        result = monthFirstDay
      }
      return result;
    },
    maxDate() {
      let now = new Date()
      return new Date(now.getFullYear(), now.getMonth() + 1, 0);
    }
  },
  methods: {
    onClear(){
      this.showKeyboard = false
      this.onCancel()
    },
    onCommitKeyboardData(data){
      this.showKeyboard = false
      let day = this.dateList.find(i => i.date === dayjs(this.selectedDate).format('YYYY-MM-DD'))
      if(day){
        day.time = data
      }
      else{
        this.dateList.push({
          date: dayjs(this.selectedDate).format('YYYY-MM-DD'),
          time: data
        })
      }
      this.selectedDate = null
      this.save()
    },
    initIosSettings(){
      const u = navigator.userAgent;
      const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if(isiOS){
        this.showIosButton = true
      }

    },
    quickAdd(){
      const time = this.$route.query.time
      if(time){
        this.selectedDate = new Date()
        this.onConfirmDate([time.slice(0,2), time.slice(2,4), '~', time.slice(4,6), time.slice(6,8)]);
        this.selectedDate = null
        this.$router.replace('/edit')
      }
    },
    onCancel(){
      this.showPicker = false
      this.dateList = this.dateList.filter(i => i.date !== dayjs(this.selectedDate).format('YYYY-MM-DD'))
      this.selectedDate = null
      this.save()
    },
    onConfirm(){
      this.$router.push('/analysis')
    },
    formatter(day){
      let date = day.date
      let now = new Date()
      if(date.getMonth() === now.getMonth() && date.getDate() === now.getDate() && date.getFullYear() === now.getFullYear()){
        day.text = '今天'
      }
      return day
    },
    dayjs: dayjs,
    generateTimeShow(item, n){
      let date = this.dateList.find(i => i.date === dayjs(item.date).format('YYYY-MM-DD'))
      if(date){
        let time = date.time
        if(n === 0){
          return time.slice(0,2) + ':' + time.slice(2, 4)
        }
        else {
          return time.slice(4,6) + ':' + time.slice(6,8)
        }
      }
      else{
        return ''
      }
    },
    formatNumber(num){
      num = num.toString()
      return num[1] ? num : '0' + num
    },
    onSelectDate(date1) {
      this.selectedDate = date1
      let date = this.dateList.find(i => i.date === dayjs(date1).format('YYYY-MM-DD'))
      let defaultIndex1 = 2
      let defaultIndex2 = 0
      let defaultIndex3 = 6
      let defaultIndex4 = 0
      let array1 = Array.from({length: 5}, (val, i) => this.formatNumber(i + 7))
      let array2 = Array.from({length: 60}, (val, i) => this.formatNumber(i))
      let array3 = Array.from({length: 12}, (val, i) => this.formatNumber(i + 12))
      let array4 = Array.from({length: 60}, (val, i) => this.formatNumber(i))
      if(date){
        let time1 = (date.time.slice(0,2))
        let time2 = date.time.slice(2,4)
        let time3 = date.time.slice(4,6)
        let time4 = date.time.slice(6,8)
        defaultIndex1 = array1.findIndex(i => this.formatNumber(i) === time1)
        defaultIndex2 = array2.findIndex(i => this.formatNumber(i) === time2)
        defaultIndex3 = array3.findIndex(i => this.formatNumber(i) === time3)
        defaultIndex4 = array4.findIndex(i => this.formatNumber(i) === time4)
      }
      const useQuickAdd = localStorage.getItem("useQuickAdd") !== '0'
      if(useQuickAdd){
        this.showKeyboard = true
      }
      else{
        this.columns = [
          {
            values: array1,
            defaultIndex: defaultIndex1,
          },
          {
            values: array2,
            defaultIndex: defaultIndex2,
          },
          {
            values: ['~'],
            defaultIndex: 0,
          },
          {
            values: array3,
            defaultIndex: defaultIndex3,
          },
          {
            values: array4,
            defaultIndex: defaultIndex4,
          },
        ];
        this.showPicker = true
      }
    },
    onConfirmDate(result){
      let day = this.dateList.find(i => i.date === dayjs(this.selectedDate).format('YYYY-MM-DD'))
      if(day){
        day.time = result[0] + result[1] + result[3] + result[4]
      }
      else{
        this.dateList.push({
          date: dayjs(this.selectedDate).format('YYYY-MM-DD'),
          time: result[0] + result[1] + result[3] + result[4]
        })
      }
      this.showPicker = false
      this.selectedDate = null
      this.save()
    },
    save(){
      localStorage.setItem("record", JSON.stringify(this.dateList))
    },
    initData(){
      let list = localStorage.getItem("record")
      if(list){
        list = JSON.parse(list)
        let now = new Date()
        let minDate = new Date(now.getFullYear(), now.getMonth() -1 , 1);
        list = list.filter(i => i.date <= dayjs(this.maxDate).format('YYYY-MM-DD') && i.date >= dayjs(minDate).format('YYYY-MM-DD'))
        this.dateList = list
      }
    }
  },
  watch:{
    $route(newQuery, oldQuery){
      if(newQuery.query.time){
        this.quickAdd()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.main{
  padding-bottom: 20px;
}
.ios_link{
  color: #227ba2;
  text-decoration: underline;
  text-align: center;
  width: 100%;
  display: block;
  font-size: 12px;
}
</style>
<style lang="scss" >
.main {
  .van-calendar__day{

  }
  .van-calendar__day, .van-calendar__selected-day{
    align-items: flex-start;
    box-sizing: border-box;
    padding-top: 20px;
  }
  .van-calendar__selected-day{
    position: relative;
    bottom: 20px;
  }
  .start{
    background: #C8E4B2;
    color: black;
  }
  .end{
    background: #9ED2BE;
    color: white;
  }
  .van-ellipsis{
    overflow: visible;
  }
}

</style>